package linfei.controller;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FilenameUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import linfei.pojo.Books;
import linfei.service.BooksMapperService;
import linfei.util.ResultGridStore;
import linfei.util.ResultMsg;
/**
 * 图书-控制层
 * 
 * @author 林飞
 * @author wfeil211@foxmail.com
 */
@Controller
@RequestMapping("BooksController")
public class BooksController implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final Logger logger = Logger.getLogger(BooksController.class);

	@Autowired
	private BooksMapperService booksMapperService;
	/**
	 * 表单获取
	 * @param books
	 * @param start
	 * @param limit
	 * @return ResultGridStore
	 */
	@RequestMapping("/getGridStore")
	@ResponseBody
	public ResultGridStore getGridStore(Books books,Integer start,Integer limit){
		ResultGridStore rgs=new ResultGridStore();
		try{
			rgs.setList(booksMapperService.serviceQuery(books, start, limit));
			rgs.setTotalProperty(booksMapperService.serviceTotal(books));
		}catch(Exception e){
			e.printStackTrace();
			logger.error("系统出错!", e);
		}
		return rgs;
	}
	/**
	 * 添加图书
	 * @param books
	 * @return ResultMsg
	 */
	@RequestMapping("/addBook")
	@ResponseBody
	public ResultMsg addBook(Books books,HttpServletRequest request){
		ResultMsg rsg=new ResultMsg();
		try{
			Books isbn=new Books();
			isbn.setIsbn(books.getIsbn());
			List<Books> bo=booksMapperService.serviceQuery(isbn, 0, 10);
			if(bo.size()>0){
				rsg.setExecute(false);
				rsg.setSuccess(false);
				rsg.setMsg("图书编号必须唯一，请重输!");
				return rsg;
			}
			books.setCreatetime(new Date());
			/**
			 * 文件获取
			 */
			MultipartHttpServletRequest resources = (MultipartHttpServletRequest) request;
			List<MultipartFile> imgoneFile = resources.getFiles("imageFile");
			List<MultipartFile> reportFile = resources.getFiles("reportFile");
			List<MultipartFile> videoFile = resources.getFiles("videoFile");
			if(imgoneFile.size()>0){
				for (MultipartFile file : imgoneFile) {
					String fileName = file.getOriginalFilename();	//文件名
					String suffix = fileName.substring(fileName.lastIndexOf("."));
					String scName = Calendar.getInstance().getTimeInMillis() + "" + (int) (1 + Math.random() * 1000)
							+ suffix;
					String realPath = request.getSession().getServletContext().getRealPath("/statics/upload/books");
					File fil=new File(realPath,scName);
					if (!fil.exists()){//如果fil代表的文件不存在，则创建它，
						fil.mkdirs();//
		            }
					file.transferTo(fil);
					books.setImage(request.getContextPath()+"/statics/upload/books/"+fil.getName());
				}
			}
			if(reportFile.size()>0){
				for (MultipartFile file : reportFile) {
					String fileName = file.getOriginalFilename();	//文件名
					String suffix = fileName.substring(fileName.lastIndexOf("."));
					String scName = Calendar.getInstance().getTimeInMillis() + "" + (int) (1 + Math.random() * 1000)
							+ suffix;
					String realPath = request.getSession().getServletContext().getRealPath("/statics/upload/multimedia");
					File fil=new File(realPath,scName);
					if (!fil.exists()){//如果fil代表的文件不存在，则创建它，
						fil.mkdirs();//
		            }
					file.transferTo(fil);
					books.setMultimedia(request.getContextPath()+"/statics/upload/multimedia/"+fil.getName());
				}
			}
			if(videoFile.size()>0){
				for (MultipartFile file : videoFile) {
					String fileName = file.getOriginalFilename();	//文件名
					String suffix = fileName.substring(fileName.lastIndexOf("."));
					String scName = Calendar.getInstance().getTimeInMillis() + "" + (int) (1 + Math.random() * 1000)
							+ suffix;
					String realPath = request.getSession().getServletContext().getRealPath("/statics/upload/video");
					File fil=new File(realPath,scName);
					if (!fil.exists()){//如果fil代表的文件不存在，则创建它，
						fil.mkdirs();//
		            }
					file.transferTo(fil);
					books.setVideo(request.getContextPath()+"/statics/upload/video/"+fil.getName());
				}
			}
			booksMapperService.serviceInsert(books);
			rsg.setExecute(true);
			rsg.setSuccess(true);
			rsg.setMsg("添加成功!");
		}catch(Exception e){
			rsg.setExecute(false);
			rsg.setSuccess(false);
			rsg.setMsg("系统出错!");
			e.printStackTrace();
			logger.error("系统出错!", e);
		}
		return rsg;
	}
	/**
	 * 修改图书
	 * @param books
	 * @return ResultMsg
	 */
	@RequestMapping("/editBook")
	@ResponseBody
	public ResultMsg editBook(Books books,HttpServletRequest request){
		ResultMsg rsg=new ResultMsg();
		try{
			Books isbn=new Books();
			isbn.setIsbn(books.getIsbn());
			List<Books> bo=booksMapperService.serviceQuery(isbn, 0, 10);
			if(bo.size()>0){
				if(!(bo.get(0).getId().equals(books.getId()))){
					rsg.setExecute(false);
					rsg.setSuccess(false);
					rsg.setMsg("图书编号必须唯一，请重输!");
					return rsg;
				}				
			}
			/**
			 * 文件获取
			 */
			MultipartHttpServletRequest resources = (MultipartHttpServletRequest) request;
			List<MultipartFile> imgoneFile = resources.getFiles("imageFile");
			List<MultipartFile> reportFile = resources.getFiles("reportFile");
			List<MultipartFile> videoFile = resources.getFiles("videoFile");
			if(imgoneFile.size()>0){
				for (MultipartFile file : imgoneFile) {
					String fileName = file.getOriginalFilename();	//文件名
					String suffix = fileName.substring(fileName.lastIndexOf("."));
					String scName = Calendar.getInstance().getTimeInMillis() + "" + (int) (1 + Math.random() * 1000)
							+ suffix;
					String realPath = request.getSession().getServletContext().getRealPath("/statics/upload/books");
					File fil=new File(realPath,scName);
					if (!fil.exists()){//如果fil代表的文件不存在，则创建它，
						fil.mkdirs();//
		            }
					file.transferTo(fil);
					books.setImage(request.getContextPath()+"/statics/upload/books/"+fil.getName());
				}
			}
			if(reportFile.size()>0){
				for (MultipartFile file : reportFile) {
					String fileName = file.getOriginalFilename();	//文件名
					String suffix = fileName.substring(fileName.lastIndexOf("."));
					String scName = Calendar.getInstance().getTimeInMillis() + "" + (int) (1 + Math.random() * 1000)
							+ suffix;
					String realPath = request.getSession().getServletContext().getRealPath("/statics/upload/multimedia");
					File fil=new File(realPath,scName);
					if (!fil.exists()){//如果fil代表的文件不存在，则创建它，
						fil.mkdirs();//
		            }
					file.transferTo(fil);
					books.setMultimedia(request.getContextPath()+"/statics/upload/multimedia/"+fil.getName());
				}
			}
			if(videoFile.size()>0){
				for (MultipartFile file : videoFile) {
					String fileName = file.getOriginalFilename();	//文件名
					String suffix = fileName.substring(fileName.lastIndexOf("."));
					String scName = Calendar.getInstance().getTimeInMillis() + "" + (int) (1 + Math.random() * 1000)
							+ suffix;
					String realPath = request.getSession().getServletContext().getRealPath("/statics/upload/video");
					File fil=new File(realPath,scName);
					if (!fil.exists()){//如果fil代表的文件不存在，则创建它，
						fil.mkdirs();//
		            }
					file.transferTo(fil);
					books.setVideo(request.getContextPath()+"/statics/upload/video/"+fil.getName());
				}
			}
			booksMapperService.serviceUpdateByPrimaryKeySelective(books);
			rsg.setExecute(true);
			rsg.setSuccess(true);
			rsg.setMsg("修改成功!");
		}catch(Exception e){
			rsg.setExecute(false);
			rsg.setSuccess(false);
			rsg.setMsg("系统出错!");
			e.printStackTrace();
			logger.error("系统出错!", e);
		}
		return rsg;
	}
	/**
	 * 批量删除
	 * @param ids
	 * @return ResultMsg
	 */
	@RequestMapping("/delBook")
	@ResponseBody
	public ResultMsg delBook(String ids){
		ResultMsg msg = new ResultMsg();
		try {
			if (!(StringUtils.isEmpty(ids))) {
					int row = booksMapperService.serviceBatchDelete(ids);
					if (row > 0) {
						msg.setExecute(true);
						msg.setSuccess(true);
						msg.setMsg("删除成功!");
					} else {
						msg.setExecute(false);
						msg.setSuccess(false);
						msg.setMsg("删除失败!");
					}
			} else {
				msg.setExecute(false);
				msg.setSuccess(false);
				msg.setMsg("数据传输失败!");
			}
		} catch (Exception e) {
			msg.setExecute(false);
			msg.setSuccess(false);
			msg.setMsg("系统出错!");
			e.printStackTrace();
			logger.error("系统出错!", e);
		}
		return msg;
	}
	/**
	 * 多媒体上传
	 * @return List<Map<String,String>>
	 */
	@RequestMapping("/upload")
	@ResponseBody
	public List<Map<String,String>> upload(@RequestParam MultipartFile[] reportFile,HttpServletRequest request,HttpServletResponse response){
        String realPath =request.getSession().getServletContext().getRealPath("/statics/upload/multimedia");
        File file = new File(realPath);
        if (!file.exists()) {//文件夹不存在 创建文件夹
            file.mkdirs();
        }
        response.setContentType("text/plain; charset=UTF-8");
        List<Map<String,String>> list = new ArrayList<Map<String,String>>();
        String originalFilename = null;
        for(MultipartFile myfile : reportFile){
            Map<String,String> map = new HashMap<String,String>();
            if(myfile.isEmpty()){
                logger.info("请选择文件后上传!");
                return null;
            }else{
                originalFilename = myfile.getOriginalFilename();
                String extension =FilenameUtils.getExtension(originalFilename);
                if("jpg".equalsIgnoreCase(extension)||"png".equalsIgnoreCase(extension)||"mp4".equalsIgnoreCase(extension)||"zip".equalsIgnoreCase(extension)){
                    originalFilename=System.currentTimeMillis()+"."+FilenameUtils.getExtension(originalFilename);
                    try {
                        myfile.transferTo(new File(realPath, originalFilename));
                        //保存文件路径
                        map.put("pathUrl",request.getContextPath()+"/statics/upload/multimedia/"+originalFilename);
 
                        list.add(map);
                        logger.info("load success " );
                    }catch (Exception e) {
                        logger.info("文件[" + originalFilename + "]上传失败,堆栈轨迹如下");
                        e.printStackTrace();
                        logger.info("文件上传失败，请重试！！");
                        return null;
                    }
                }else{
                    logger.info("load success 只支持jpg,png,mp4,zip格式");
                }
            }
        }
        return list;
	}
	/**
	 * 视频上传
	 * @return List<Map<String,String>>
	 */
	@RequestMapping("/videoUpload")
	@ResponseBody
	public List<Map<String,String>> videoUpload(@RequestParam MultipartFile[] videoFile,HttpServletRequest request,HttpServletResponse response){
        String realPath =request.getSession().getServletContext().getRealPath("/statics/upload/video");
        File file = new File(realPath);
        if (!file.exists()) {//文件夹不存在 创建文件夹
            file.mkdirs();
        }
        response.setContentType("text/plain; charset=UTF-8");
        List<Map<String,String>> list = new ArrayList<Map<String,String>>();
        String originalFilename = null;
        for(MultipartFile myfile : videoFile){
            Map<String,String> map = new HashMap<String,String>();
            if(myfile.isEmpty()){
                logger.info("请选择文件后上传!");
                return null;
            }else{
                originalFilename = myfile.getOriginalFilename();
                String extension =FilenameUtils.getExtension(originalFilename);
                if("mp4".equalsIgnoreCase(extension)){
                    originalFilename=System.currentTimeMillis()+"."+FilenameUtils.getExtension(originalFilename);
                    try {
                        myfile.transferTo(new File(realPath, originalFilename));
                        //保存文件路径
                        map.put("pathUrl",request.getContextPath()+"/statics/upload/video/"+originalFilename);
 
                        list.add(map);
                        logger.info("load success " );
                    }catch (Exception e) {
                        logger.info("文件[" + originalFilename + "]上传失败,堆栈轨迹如下");
                        e.printStackTrace();
                        logger.info("文件上传失败，请重试！！");
                        return null;
                    }
                }else{
                    logger.info("load success 只支持mp4格式");
                }
            }
        }
        return list;
	}
}
